1. Using modelflow with World Bank models

The Modelflow python package has been developed to solve a wide range of models, see the modelflow github web site for working examples of the Solow Model, the FR/USB model and others.

The package has been substantially expanded to include special features that enable it to work with World Bank models originally developed in EViews and designed to use EViews Model Object for simuation.

This chapter illustrates how to access these models, how to load them into a modelflow anaconda environment on your computer and how to perform a variety of simulations

1.1. Accessing a world bank model

At this time several World bank macrostructural models are available to download and use with modelflow. These include a macrostructural model for:

  • Indonesia

  • Nepal

  • Croatia

  • Iraq

  • Kenya

  • Bolivia

Each of these models has been developed as part of the outreach work of the World Bank. The basic modelling framework of each of these models is outlined in Burns et al. [2019] with specific extensions reflecting features of the individual country modelled.

This book uses as an example a climate aware model for Pakistan developed in 2020 and described in Burns et al. [2021] .

The World Bank models are distributed in the pcim file format of the modelflow and can be downloaded by right clicking on the links above. The Pakistan model can be downloaded here by right clicking on the above link and selecting Save Link as and placing the file on a directory accessible by your modelflow installation.

Ib can't we have a package WorldBankMFModModels that one could import? I seem to see this for other packages that have geographic data on countries or their population. I imagining something like:

from worldbankMFModModels import pak

1.2. Preparing your python environment

As always, the modelflow and other python packages that will be used need to be imported into your python session. The examples here and this book were written and solved in a Jupyter Notebook. There are some Jupyter specific commands included in these examples and these are annotated. However, the bulk of the content of the programs can be run in other environments, including Interactive Development Environments (IDE) like Spyderor MS Visual Code. All the programs have been tested under spyder as well as Jupyter Notebook.

It is assumed that:

  1. you have already installed modelflow and its various support packages following the instructions in Chapter xx

  2. you are using Anaconda, and that

  3. you have activated your modelflow environment by executing the following command from your python command line:

conda activate modelflow

where modelflow is the name you have given to the conda environment into which you installed modelflow.

# import the model class from modelflow package
from modelclass import model 
import modelmf       # Add useful features to pandas dataframes 
                     # using utlities initially developed for modelflow

   

model.widescreen()   # These modelflow commands ensure that outputs from modelflow play well with Jupyter Notebook
model.scroll_off()

%load_ext autoreload   
%autoreload 2

1.3. Working with PakMod under modelflow

The basic method for working with any model is the same. Indeed the initial steps followed here are the same as were followed during the simple model discussion.

Process:

  1. Prepare the workspace

  2. Load the model Modelflow

  3. Design some scenarios

  4. Simulate the model

  5. Visualize the results

1.3.1. Load a pre-existing model, data and descriptions

To load a model use the model.modelload() method of modelflow.

The command below

mpak,bline = model.modelload('C:\mflow\modelflow-manual\papers\mfbook\content\models\pak.pcim', alfa=0.7,run=1,keep= 'Baseline')

instantiates (creates an instance of) a modelflow model object and assigns it to the variable name mpak. The run=1 option executes the model and assigns the result of the model execution to the dataframe bline. The model is solved with the parameter alfa set to 0.7. The \(alfa \in (0,1)\) parameter determines the step size of the solution engine. The larger alfa the larger the step size. Larger step sizes solve faster, but may have trouble finding a unique solution. Smaller step sizes take longer to solve but are more likely to find a unique solution. Values of alfa=.7 work well for World Bank models.

The keep option instructs modelflow to maintain in the model object (mpak) the results of the intitial scenario, assigning it the text name Baseline.

#Replace the path below with the location of the pak.pcim file on your computer
mpak,bline = model.modelload('C:\mflow\modelflow-manual\papers\mfbook\content\models\pak.pcim', \
                                alfa=0.7,run=1,keep= 'Baseline')
file read:  C:\mflow\modelflow-manual\papers\mfbook\content\models\pak.pcim

Note

the variable bline contains the dataframe with the results of the simulation. This is distinct from the data that is stored by the kept= command. That said, the data associated with each, while stored separately, have the same numerical values. The keep option is described in more detail toward the end of this section.

Box [^BoxWBMnemonics]: World Bank Mnemonics

A typical World Bank model will have in excess of 300 variables. Each has a mnemonic that is structured in a specific way, The root for almost all are 14 characters long (some special variables have additional characters appended to this root) (see discussion in section).

\[\texttt{12345678901234}\]
\[\color{green}{\texttt{CCC}}\color{red}{\texttt{AA}}\color{lime}{\texttt{MMM}}\color{blue}{\texttt{NNNN}}\color{magenta}{\texttt{U}}\color{black}{\texttt{C}}\]

where:

Letters

Meaning

\(\color{green}{\texttt{CCC}}\)

The three-leter ISO code for a country – i.e. IDN for Indonesia, RUS for Russia

\(\color{red}{\texttt{AA}}\)

The two-letter major accounting system to which the variable attaches,

\(\color{lime}{\texttt{MMM}}\)

The three-letter major sub-category of the data - i.e. GDP, EXP - expenditure

\(\color{blue}{\texttt{NNNN}}\)

The four-letter minor sub-category MKTP for market prices

\(\color{magenta}{\texttt{U}}\)

The measure (K: real variable;C: Current Values; X: Prices)

\(\color{black}{\texttt{C}}\)

denotes the Currency (N: National currency; D: USD; P: PPP)

Common major accounting systems mnemonics: the, \(\color{red}{\texttt{AA}}\)s from above:

Code

Meaning

NY

National income

NE

National expenditure Accounts

NV

Value added accounts

GG

General Government Accounts

BX

Balance of Payments: Exports

BM

Balance of Payments: Imports

BN

Balance of Payments: Net

BF

Balance of Payments: Financial Account

Thus

Mnemonic

Meaning

IDNNYGDPMKTPKN

Indonesia GDP at market prices, real in Indonesian Rupiah

KENNECPNPRVTXN

Kenya Private (household) consumption expenditure schillings deflator

BOLGGEXPGNFSCN

Bolivia Government Expenditure on Goods and services (GNFS) in current Bolivars

HRVGGREVDCITCN

Croatia Government Revenues Direct Corporate Income Taxes in current Euros

NPLBXGSRNFSVCD

Nepal BOP Exports of non-factor services (goods and services) in current USD

1.3.2. Extracting information about the model

The newly loaded python object mpak is an instance of the model class and as such inherits the methods (functions) and properties (data) of that class. To learn about the model there are a variety of information methods that can be used to extract information about the model and its data.

Information about a specific

Method

Example

Information returned

.des

modelname\['PAKNECONPRVTXN'\].des

Dictionary of mnemonics and their variable descriptions

.desc

modelname\['PAKNECONPRVTXN'\].desc

List of variable description alone

Note

Wildcards The * character in the command mpak['PAKNECON*XN'].names is a wildcard character and the extopression will return all variables that begin PAKNECON and end XN. the ? is another wildcard expression. It will match only single characters. Thus mpak['PAKNECONPRVT?N'].names would return three variables: PAKNECONPRVTKN, PAKNECONPRVTXN, and PAKNECONPRVTXN. The real, current value, and deflators for household consumption expenditure.

Information about anumber of variables that meet certain search criteria

The above functions can be used in conjunction with a wildcard specification to extract the same information about a number of variables that meet the criteria. To extract a list of all variables matching a pattern, we can use same methods.

Wildcards

The * operator matches multiple characters, the ? operator matches just one character

Method

Example

Information returned

.des

modelname.['*partialname*'].des

Returns Dictionary of all mnemonic and variable descriptions whose mnemonic matches

.desc

modelname.['*partialname'].desc

Returns list of variable descriptions whose mnemonic matches

.names

modelname.['*partialname'].names

Returns list of variable mnemonics that match

The ! operator If a wildcard is preceded by an exclamation mark ! the search will be done over the description of variables instead of the mnemonic

Method

Example

Information returned

.des

modelname.['!*GDP\*'].des

Returns Dictionary of all mnemonic and variable descriptions whose description contains the string GDP

.desc

modelname.['!*Consumption*'].desc

Returns list of variable descriptions whose description contains the string Consumption

.names

modelname.['!*Agriculture*'].names

Returns list of variable mnemonics whose description contains the string Agriculture

#Operator The # operator passes a predefined list to the search function and returns variable info about the variables in the list

Method

Example

Information returned

.des

modelname.['#MyList'].des

Returns Dictionary of all mnemonic and variable descriptions of the variables contained in the list MyList

.desc

modelname.['#MyList'].desc

Returns list of variable descriptions of variables contained in the list MyList

.names

modelname.['#MyList'].names

Returns list of variable mnemonics of variables contained in the list MyList

1.3.2.1. Some examples

Return all variables that begin PAKNECON and end KN.

mpak['PAKNECON*XN'].names
['PAKNECONENGYXN', 'PAKNECONGOVTXN', 'PAKNECONOTHRXN', 'PAKNECONPRVTXN']
import fnmatch

def match_desc(model,s2Match):
    reverse_des  = {v:k for k,v in model.var_description.items()}
    list_des = fnmatch.filter(reverse_des.keys(),s2Match)
    list_var = [reverse_des[v] for v in list_des]
    Results = {}
    for key, val in zip(list_var,list_des):
        Results.setdefault(key,val)
    return Results

def match_mnem(model,s2Match):
    model.var_description.items()
    list_des = fnmatch.filter(model.var_description.keys(),s2Match)
    list_var = [model.var_description[v] for v in list_des]
    Results = {}
    for key, val in zip(list_var,list_des):
        Results.setdefault(key,val)
    return Results

desc=match_desc(mpak,"*GDP*")
mnems=match_mnem(mpak,"PAKNYGDPMKTP*N")

#mpak['!*GDP*'].des #returns the des of vars whose description match the string
#mpak['#listname'].des#the descriptions of teh variables in th list
#mpak['PAKNYGDPMKTP*N'].des  #the descriptions of the mnemonics that matchg

#mpak['!*GDP*'].desc#returns the des of vars whose description match the string

Return a dictionary comprised of the mnemonics and the descriptions of all the variables that begin PAKNECONPRVT and end N, but have one character between the T and the N.

mpak['PAKNECONPRVT?N'].des
PAKNECONPRVTCN : Pvt. Cons., LCU mn
PAKNECONPRVTKN : HH. Cons Real
PAKNECONPRVTXN : PAKNECONPRVTXN

Return a list of the full description all the variables that have the word GDP in their description.

# Not yet released
#mpak['!*GDP*'].des

Return a dictionary comprised of the variable name and description if all variables in a list.

#Functionality not yet activated.
#mylist=['PAKNECONPRVTKN','PAKNECONGOVTKN','PAKNEGDIFTOTKN','PAKNEEXPGNGSKN','PAKNEIMPGNFSKN']
#mpak['#mylist'].des

1.3.2.2. Equation information methods

There are several functions to extract the equations from a model. The two most interesting are:

Command

Effect

mpak['PAKNECONPRVTKN'].frml

Returns a normalized version of the equation (the one actually used in modelflow)

mpak['PAKNECONPRVTKN'].eviews

In models imported from Eviews, reports the original eviews specification

mpak['PAKNECONPRVTKN'].original

Returns an intermediate version of the unnormalized equation. This version has replaced EViews syntax with Business Logic syntax

The equation for consumption in mpak we see that it follows something very close to this formulation.

mpak.PAKNECONPRVTKN.frml
mpak.var_description['PAKNYGDPMKTPKN']
Endogeneous: PAKNECONPRVTKN: HH. Cons Real
Formular: FRML <Z,EXO> PAKNECONPRVTKN = (PAKNECONPRVTKN(-1)*EXP(PAKNECONPRVTKN_A+ (-0.2*(LOG(PAKNECONPRVTKN(-1))-LOG(1.21203101101442)-LOG((((PAKBXFSTREMTCD(-1)-PAKBMFSTREMTCD(-1))*PAKPANUSATLS(-1))+PAKGGEXPTRNSCN(-1)+PAKNYYWBTOTLCN(-1)*(1-PAKGGREVDRCTXN(-1)/100))/PAKNECONPRVTXN(-1)))+0.763938860758873*((LOG((((PAKBXFSTREMTCD-PAKBMFSTREMTCD)*PAKPANUSATLS)+PAKGGEXPTRNSCN+PAKNYYWBTOTLCN*(1-PAKGGREVDRCTXN/100))/PAKNECONPRVTXN))-(LOG((((PAKBXFSTREMTCD(-1)-PAKBMFSTREMTCD(-1))*PAKPANUSATLS(-1))+PAKGGEXPTRNSCN(-1)+PAKNYYWBTOTLCN(-1)*(1-PAKGGREVDRCTXN(-1)/100))/PAKNECONPRVTXN(-1))))-0.0634474791568939*DURING_2009-0.3*(PAKFMLBLPOLYXN/100-((LOG(PAKNECONPRVTXN))-(LOG(PAKNECONPRVTXN(-1)))))) )) * (1-PAKNECONPRVTKN_D)+ PAKNECONPRVTKN_X*PAKNECONPRVTKN_D  $

PAKNECONPRVTKN  : HH. Cons Real
DURING_2009     : 
PAKBMFSTREMTCD  : Imp., Remittances (BOP), US$ mn
PAKBXFSTREMTCD  : Exp., Remittances (BOP), US$ mn
PAKFMLBLPOLYXN  : Key Policy Interest Rate
PAKGGEXPTRNSCN  : Current Transfers
PAKGGREVDRCTXN  : Direct Revenue Tax Rate
PAKNECONPRVTKN_A: Add factor:HH. Cons Real
PAKNECONPRVTKN_D: Fix dummy:HH. Cons Real
PAKNECONPRVTKN_X: Fix value:HH. Cons Real
PAKNECONPRVTXN  : 
PAKNYYWBTOTLCN  : 
PAKPANUSATLS    : Exchange rate LCU / US$ - Pakistan
'Real GDP'

The mpak['PAKNECONPRVTKN'].eviews command returns the equations in a slightly more legible form, where the \(\Delta ln()\) expressions are written using eviews syntax as dlog().

## This command not yet released, un comment when available.
##mpak.PAKNECONPRVTKN.eviews

1.4. Behavioural equations in the MFMod framework

Recall a behavioural equation determines the value of an endogenous variable. For many of the variables in Wold Bank models, behavioural functions are estimated using an Error Correction Framework that splits the equation into a theoretically determined long run component and a more idiosyncratic short-run component.

Remember the .frml method presents the economic equation in a normalized form.

(PAKNECONPRVTKN(-1)EXP(-PAKNECONPRVTKN_A+ (-0.2(LOG(PAKNECONPRVTKN(-1))-LOG((PAKNYYWBTOTLCN(-1)(1-PAKGGREVDRCTXN(-1)/100))/PAKNECONPRVTXN(-1)))+1((LOG((PAKNYYWBTOTLCN*(1-PAKGGREVDRCTXN/100))/PAKNECONPRVTXN))-(LOG((PAKNYYWBTOTLCN(-1)(1-PAKGGREVDRCTXN(-1)/100))/PAKNECONPRVTXN(-1))))+0.0303228629698929+0.0163839011059956DURING_2010-0.3*(PAKFMLBLPOLYXN/100-((LOG(PAKNECONPRVTXN))-(LOG(PAKNECONPRVTXN(-1)))))) )) * (1-PAKNECONPRVTKN_D)+ PAKNECONPRVTKN_X*PAKNECONPRVTKN_D

Taking logarithms of both sides of the the first expression (excluding the *(1-PAKNECONPRVTKN_D) term) and collecting the PAKNECONPRVTKNs on the left-hand side , the originally estimated ECM expression can be recovered. Below we simplify the mnemonics to ease reading of the equation using:

Model Mnemonic

Simplified

Meaning

PAKNECONPRVTKN

\(CON^{KN}_t\)

Household Consumption

DURING_2010

\(D^{2010}_t\)

A dummy

PAKFMLBLPOLYXN

\(r^{policy}_t\)

Policy Rate

PAKGGREVDRCTXN

\(DirectTxR_t\)

Direct Taxes: Effective rate

PAKNECONPRVTKN_A

\(CON^{KN_AF}_t\)

Add factor:Household Consumption

PAKNECONPRVTXN

\(CON^{XN}_t\)

Household Consumption Deflator

PAKNYYWBTOTLCN

\(WAGEBILL^{CN}_t\)

Economy-wide wage bill

\[\begin{split}\begin{align} \Delta log(CON^{KN}_t) = &-0.2*\bigg[LOG(CON^{KN}_{t-1})-LOG\bigg({\frac{WAGEBILL^{CN}_{t-1}*(1-DirectTxR_{t-1}/100)}{CON^{XN}_{t-1}}}\bigg)\bigg] \\ &+1.0*\Delta log \bigg({\frac{WAGEBILL^{CN}_{t}*(1-DirectTxR_{t}/100)}{CON^{XN}_{t}}}\bigg) \\ &+0.030 + 0.016*D^{2010}_t-0.3*\bigg(r^{policy}_t/100-\Delta log(CON^{XN}_{t})\bigg) -CON^{KN_AF}_t \end{align} \end{split}\]

Where in this instance the short-run elasticity of consumption to disposable income has been constrained to 1, and the short run elasticity of consumption to the real interest rate is 0.3.

1.4.1. The ECM specification

Pretty sure this repeats and earlier section. Delete one

The ECM approach used in World Bank models is described in [Wickens and Breusch, 1988], and addresses the above challenge by modelling both the long run relationship and the short run short run behaviour and brings them together into one equation.

The ECM specification is therefore a single equation comprised of two parts (the long run relationship, and the short-run relationship).

Consider as an example two variables say consumption and disposable income. Both have an underlying trend or in the parlance are co-integrated to degree 1. For simplicity we call them y an x.

1.4.1.1. The short run relationship

In its simplest form we might have a short run relationship between the growth rates of our two variables such that:

\[\Delta log(Y_t) = \alpha + \beta \Delta log(X_t) +\epsilon_t\]

or substituting lower case letters for the logged values.

\[\Delta y_t = \alpha + \beta \Delta x_t +\epsilon_t\]

1.4.1.2. The long run equation

The long run relates the level of the two (or more) variables. We can write a simple version of that equation as:

\[Y_t=αX_t^β+ \eta_t\]

Rewriting this (in logarithms) it can be expressed as:

\[y_t = ln⁡(α) + βy_t + \eta_t\]

1.4.2. The long run equation in the steady state

First we note that in the steady state the expected value of the error term in the long run equation is zero (\(\eta_t=0 \)) so in those conditions we can simplify the long run relationship to:

\[y_t=ln⁡(α)+\beta x_t\]

or equivalently (substituting A for the log of \(\alpha\)).

\[y_t-A-βx_t=0\]

Moreover if we multiplied this by some arbitrary constant say \(-\lambda\) it would still equal zero.

\[-\lambda(y_t -A-βx_t)\]

and in the steady state this will also be true for the lagged variables

\[-\lambda(y_{t-1-} A - βx_{t-1})\]

1.5. Putting it together

From before we have the short run equation:

\[\Delta y_t = \alpha + \beta \Delta x_t +\epsilon_t\]

Inserting the steady state expression into the short run equation makes no difference (in the long run) because in the long run it is equal to zero.

\[\Delta y_t = -\lambda(y_{t-1-}A-βx_{t-1}) + \alpha + \beta \Delta x_t +\epsilon_t\]

When the model is not in the steady state the expression \(y_{t-1}-A-βx_{t-1}\) is of course the error term from the long run equation (a measure of how far the dependent variable is from equilibrium).

1.5.1. Lambda, the speed of adjustment

The parameter \(\lambda\) can be interpreted as the speed of adjustment. As long as \(\lambda\) is greater than zero and less or equal to one if there are no further disturbances ( \(\epsilon_t=0\)) the expression multiplied by lambda will slowly decline toward zero. How fast depends on how large or small is \(\lambda\).

To be convergent \(\lambda\) must be between 0 and 2, if its is negative or greater than one, then the long run portion of the equation will cause the disequilibrium to grow each period (\(\lambda\) >1) not diminish or if (\(\lambda\) >1<2) output will oscillate from positive to negative (\(\lambda <0\)).

Intuitively, the long run error term measures how far we are from equilibrium one period earlier (at t-1). The ECM term ensures that we will slowly converge to equilibrium – the point at which the long run equation holds exactly. If $\(\lambda\)\( is greater than zero but less than one (or equal to one) some portion of the previous period year's disequilibrium will be absorbed each year. How much is absorbed depends on the size of estimated speed of the adjustment coefficient \)\lambda$.

Looking at an ECM equation we can then break it up into its component parts. For the consumption function it will look something like this:

\[\Delta c_t = -\lambda (\underbrace{ log(C_{t-1})-log(Wages_{t-1}-Taxes_{t-1}+Transfers_{t-1} + \alpha)} _\text{Long run} +\beta \underbrace{\Delta y_t}_\text{short run}\]